package com.nativetalk.service.member.login;

import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.member.*;
import com.nativetalk.bean.rongyun.RongCloudConfig;
import com.nativetalk.bean.rongyun.TokenResult;
import com.nativetalk.bean.user.TdNtUserLoginLog;
import com.nativetalk.common.Constants;
import com.nativetalk.common.ValidationMessages;
import com.nativetalk.common.rongCloud.RongCloud;
import com.nativetalk.common.util.*;
import com.nativetalk.dao.DiscountCouponDao;
import com.nativetalk.dao.MembNewUserScholarshipDao;
import com.nativetalk.dao.TdNtMemberDao;
import com.nativetalk.dao.TdNtUserLoginLogDao;
import com.tls.tls_sigature.tls_sigature;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lizhun on 15/12/24.
 */
@Service
public class MemberLoginServiceImpl implements MemberLoginService {
    private static Logger logger = Logger.getLogger(MemberLoginServiceImpl.class);
    private static String WAIJIAOJUN_URL = "file.waijiaojun.com/";
    @Resource
    private TdNtMemberDao tdNtMemberDao;
    @Resource
    private TdNtUserLoginLogDao tdNtUserLoginLogDao;
    @Resource
    private RongCloudConfig rongCloudConfig;

    @Resource
    private MembNewUserScholarshipDao membNewUserScholarshipDao;

    @Resource
    private DiscountCouponDao discountCouponDao;

    @Override
    @Transactional
    public RetInfo login(TdNtMemberLogin user, int version, String ip) {
        String logInfo = this.getClass().getName() + ":login:";
        logger.info("======" + logInfo + "begin======");
        TokenResult tokenResult = null;
        RetInfo retInfo = new RetInfo();
        try {
            TdNtMember tdNtMember = tdNtMemberDao.findTdNtMemberByPhone(user.getMemb_phone());

            if (tdNtMember != null && tdNtMember.getMemb_password() != null) {
                TdNtUserLoginLog tdNtUserLoginLog = new TdNtUserLoginLog();
                tdNtUserLoginLog.setUser_id(tdNtMember.getMemb_id());
                tdNtUserLoginLog.setUser_type(Integer.parseInt(Constants.user_type_student));
                tdNtUserLoginLog.setYyyymm(CommonUtil.getMonth(new Date()));
                tdNtUserLoginLog.setLogin_ip(ip);
                tdNtUserLoginLog.setEqu_client_id(tdNtMember.getEqu_client_id() + "||" + user.getEqu_client_id());//设备标识
                tdNtUserLoginLog.setEqu_type(user.getEqu_type());//设备类型
                tdNtUserLoginLog.setAccount(user.getMemb_phone());//登录账号
                tdNtUserLoginLog.setOld_token(tdNtMember.getToken());
                tdNtUserLoginLog.setUid(tdNtMember.getUid());

                if (tdNtMember.getMemb_password().equals(MD5.code(user.getMemb_password()))) {
                    if (tdNtMember.getMemb_islock().equals("1")) {
                        /**
                         * 更新用户token
                         */
                        TdNtMemberToken tdNtMemberToken = new TdNtMemberToken();
                        tdNtMemberToken.setMemb_id(tdNtMember.getMemb_id());
                        tdNtMemberToken.setToken(CommonUtil.getToken());
                        tdNtMemberToken.setEqu_client_id(user.getEqu_client_id());
                        tdNtMemberToken.setEqu_type(user.getEqu_type());
                        tdNtMemberToken.setThird_token(null);
                        tdNtMemberToken.setNowLoginType(Constants.ThirdPartyType.mobile_Type);
                        tdNtMemberDao.updateTdNtMemberInfo(tdNtMemberToken);
                        /**
                         * 删除把用户对象放入memcached原有用户对象
                         */
                        MemcachedUtils.delete(tdNtMember.getToken());
                        /**
                         * 把用户对象放入memcached
                         */
                        tdNtMember.setToken(tdNtMemberToken.getToken());
                        tdNtMember.setEqu_client_id(tdNtMemberToken.getEqu_client_id());
                        tdNtMember.setEqu_type(tdNtMemberToken.getEqu_type());
                        MemcachedUtils.add(tdNtMemberToken.getToken(), tdNtMember, 20 * 24 * 60 * 60);


                        Map<String, Object> map = new HashMap<>();
                        if (StringUtil.isBlank(tdNtMember.getRongcloud_token())) {
                            // 获取融云 Token 方法
                            map.put("rongCloudToken", receiveRongCloudTokenForStudent(tdNtMember.getMemb_id()));
                        } else {
                            map.put("rongCloudToken", tdNtMember.getRongcloud_token());
                        }
                        //判断用户有没有领取优惠券，没有的话默认领取
                        int reserve_package = tdNtMemberDao.findUseReservePackage(tdNtMember.getMemb_id());
                        Date date = DateUtil.createDate("2018-06-01 00:00:00");
                        if (reserve_package == 0 && tdNtMember.getMemb_register_time().after(date)) {
                            //用户领取红包
                            // 1. 添加红包领取记录
                            MembNewUserScholarship pojo = new MembNewUserScholarship(tdNtMember.getMemb_id());
                            membNewUserScholarshipDao.insert(pojo);

                            // 2.添加到优惠券表中
                            DiscountCoupon discountCoupon = new DiscountCoupon();
                            discountCoupon.setCourse_type(1);
                            discountCoupon.setMemb_id(tdNtMember.getMemb_id());
                            discountCoupon.setDeleted(0);
                            discountCoupon.setOver((double) 0);
                            discountCoupon.setSubtract((double) 120);
                            discountCoupon.setDiscount_state(0);
                            discountCouponDao.insertDiscountCoupon(discountCoupon);
                        }
                        map.put("token", tdNtMemberToken.getToken());
                        if (version >= 5) {
                            map.put("sig", tls_sigature.getUsersig(Constants.member + tdNtMember.getMemb_id()));
                            map.put("Identifier", Constants.member + tdNtMember.getMemb_id());

                        }
                        map.put("uid", tdNtUserLoginLog.getUid());

                        retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                        retInfo.setTip(ValidationMessages.getValue("LOGIN.SUCCESS"));
                        retInfo.setObj(map);
                        tdNtUserLoginLog.setIs_success("0");
                        tdNtUserLoginLog.setLogin_failer_desc("登录成功");
                        tdNtUserLoginLog.setUid(tdNtUserLoginLog.getUid());
                    } else {
                        retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                        retInfo.setTip("账号已锁定,请联系客服");
                        tdNtUserLoginLog.setIs_success("1");
                        tdNtUserLoginLog.setLogin_failer_desc("账号锁定");
                    }

                } else {
                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                    retInfo.setTip(ValidationMessages.getValue("LOGIN.ERROR"));
                    tdNtUserLoginLog.setIs_success("1");
                    tdNtUserLoginLog.setLogin_failer_desc("密码错误");
                }
                tdNtUserLoginLogDao.insertTdNtUserLoginLog(tdNtUserLoginLog);
            } else {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip(ValidationMessages.getValue("LOGIN.ERROR"));
            }

        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    @Transactional
    public RetInfo out(TdNtMember tdNtMember) {
        String logInfo = this.getClass().getName() + ":out:";
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            TdNtMemberToken tdNtMemberToken = new TdNtMemberToken();
            tdNtMemberToken.setMemb_id(tdNtMember.getMemb_id());
            tdNtMemberToken.setToken(CommonUtil.getToken());
            tdNtMemberToken.setEqu_client_id(tdNtMember.getEqu_client_id());
            tdNtMemberToken.setEqu_type(tdNtMember.getEqu_type());

            //如果删除缓存失败，则要求用户重新退出，不能更新token
            //出现过：缓存中有token，但是数据库中没有token的情况
            MemcachedUtils.delete(tdNtMember.getToken());
            tdNtMemberDao.updateTdNtMemberToken(tdNtMemberToken);
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("退出成功");
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    public RetInfo updateEquClientId(int memb_id, String equ_client_id, String equ_type) {
        RetInfo retInfo = new RetInfo();
        if (equ_client_id == null || "".equals(equ_client_id.trim())) {
            retInfo.setMark(ValidationMessages.getValue("MARKNO"));
            retInfo.setTip("无效参数：equ_client_id不能为空");
            return retInfo;
        } else if (equ_type == null || "".equals(equ_type.trim())) {
            retInfo.setMark(ValidationMessages.getValue("MARKNO"));
            retInfo.setTip("无效参数：equ_type不能为空");
            return retInfo;
        }
        try {
            //更新数据库
            tdNtMemberDao.updateEquClientIdByMembId(memb_id, equ_client_id, equ_type);
            //更新缓存
            TdNtMember tdNtMember = tdNtMemberDao.findMember(memb_id);
            tdNtMember.setEqu_client_id(equ_client_id);
            tdNtMember.setEqu_type(equ_type);
            MemcachedUtils.replace(tdNtMember.getToken(), tdNtMember, 20 * 24 * 60 * 60);
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("更新DeviceToken成功");
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        return retInfo;
    }

    public String receiveRongCloudTokenForStudent(Integer memb_id) {
        try {
            TdNtMember member = tdNtMemberDao.findMember(memb_id);
            String appKey = rongCloudConfig.getAppkey();
            String appSecret = rongCloudConfig.getSecret();
            // 获取融云 Token 方法
            RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
            String ront_memb_id = "student" + memb_id;
            String avatar = CommonUtil.getFullUri(member.getMemb_head_portrait());
            TokenResult tokenResult = rongCloud.user.getToken(ront_memb_id, member.getMemb_name(), avatar);
            logger.info("获取融云token返回---》" + JsonUtil.toJson(tokenResult));
            tdNtMemberDao.updateRongCloudToken(tokenResult.token, memb_id);
            if (tokenResult.getToken() != null && tokenResult.getToken() != "") {
                return tokenResult.getToken();
            } else {
                throw new RuntimeException("获取融云token异常：" + tokenResult.errorMessage);
            }
        } catch (Exception e) {
            logger.error("获取融云token异常", e);
            throw new RuntimeException("获取融云token异常");
        }
    }
}
